`
https://leetcode.cn/problems/count-the-number-of-good-subarrays/
`

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var countGood = function (nums, k) {
  const n = nums.length
  const cnt = new Map()
  let pairs = 0
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const n1 = nums[right++]
    // 窗口中有 c 个元素 x ，新元素进入，新增 c 对
    const c1 = cnt.get(n1) || 0
    pairs += c1
    cnt.set(n1, c1 + 1)

    // 关注 left - 1 的合法性
    while (pairs >= k) {
      const n2 = nums[left++]
      // 窗口中有 c 个元素 x ，删掉元素，减少 c - 1 对
      const c2 = cnt.get(n2)
      pairs -= c2 - 1
      cnt.set(n2, c2 - 1)
    }

    // 有 left 个
    res += left
  }

  return res
};